package org.cliff.message.platform.ext.lock;

import org.cliff.message.platform.core.util.IDistributeLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * Redisson分布式锁实现
 * @author 刘文
 * @date 2023/10/24
 */
@Slf4j
public class RedissonDistributeLockImpl implements IDistributeLock {

    /**
     * 自动注入
     */
    private RedissonClient redissonClient;

    public RedissonDistributeLockImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean tryLock(String lockName, long waitTime, long leaseTime, TimeUnit unit) {
        RLock lock = redissonClient.getLock(lockName);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            log.error("获取分布式锁被唤醒", e);
            return false;
        }
    }

    @Override
    public void unlock(String lockName) {
        RLock lock = redissonClient.getLock(lockName);
        lock.unlock();
    }
}
